import { Link } from 'react-router-dom'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
  message
} from 'antd'

import defaultImage from '../../assets/images/defaultImage.png'
import Channel from '../../components/Channel'
import { http } from '../../utils'
import { useEffect, useState } from 'react'

const { RangePicker } = DatePicker
const { confirm } = Modal

// 通过对象来优化if/switch
const articleStatus = {
  0: { text: '草稿', color: 'gold' },
  1: { text: '待审核', color: 'lime' },
  2: { text: '审核通过', color: 'green' },
  3: { text: '审核失败', color: 'red' }
}

let queryParams = {}

const ArticleList = () => {
  const [articles, setArticles] = useState({})

  // 表格的配置项
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: data => {
        return (
          <img
            src={data.images[0] || defaultImage}
            alt=""
            width={200}
            height={150}
          />
        )
      }
    },
    {
      title: '标题',
      dataIndex: 'title'
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => {
        const tagObj = articleStatus[data]
        return <Tag color={tagObj.color}>{tagObj.text}</Tag>
      }
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space>
            <Link to={`/home/publish/${data.id}`}>
              <Button
                type="primary"
                shape="circle"
                icon={<EditOutlined />}
              ></Button>
            </Link>
            {/* 删除按钮 */}
            <Button
              type="primary"
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => deleteArticle(data.id)}
            ></Button>
          </Space>
        )
      }
    }
  ]

  // 删除文章
  const deleteArticle = id => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除该文章, 是否继续?',
      onOk: async () => {
        const res = await http.delete(`/mp/articles/${id}`)
        if (res.data.message === 'OK') {
          // 提供删除成功
          message.success('删除成功', 0.6)
          getList({
            ...queryParams,
            page: page || 1
          })
        }
      }
    })
  }

  useEffect(() => {
    // 获取文章列表数据
    getList()
  }, [])

  // Form 的 提交事件
  const query = async values => {
    // 表单中拿到的数据，无法直接作为接口的参数来使用，所以，需要对数据做处理
    const { status, channel_id, date } = values

    // 先处理状态：不传为全部，全部这一项的值为 -1
    if (status !== -1) {
      queryParams.status = status
    }

    // 处理频道
    if (channel_id) {
      queryParams.channel_id = channel_id
    }

    // 处理日期
    if (date) {
      // begin_pubdate
      const begin_pubdate = date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
      // end_pubdate
      const end_pubdate = date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
      queryParams.begin_pubdate = begin_pubdate
      queryParams.end_pubdate = end_pubdate
    }

    queryParams.page = 1

    // 调用封装好的方法
    getList(queryParams)
  }

  // 创建一个方法，用来封装 获取文章列表数据 的功能
  const getList = async params => {
    // 参数默认值的原始写法
    params = params || {}
    const res = await http.get('/mp/articles', {
      params
    })
    setArticles(res.data.data)
  }

  // 切换分页
  const changePage = (page, pageSize) => {
    queryParams.page = page
    queryParams.pageSize = pageSize

    getList(queryParams)
  }

  const { page, per_page, results, total_count } = articles

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form
          initialValues={{
            status: -1
          }}
          onFinish={query}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel width={200} />
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`根据筛选条件共查询到 ${total_count} 条结果：`}>
        <Table
          columns={columns}
          dataSource={results}
          rowKey="id"
          pagination={{
            position: ['bottomCenter'],
            current: page,
            pageSize: per_page,
            total: total_count,
            onChange: changePage
          }}
        />
      </Card>
    </div>
  )
}

export default ArticleList
